<?php

namespace App\Repository\Product;

use App\Models\Product\GoodsModel as model;
use App\Repository\BaseRepository;
use App\Repository\UploadRepository;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class GoodsRepository extends BaseRepository
{
    private $model;
    private $productModel;
    private $log;

    public function __construct()
    {
        $this->model = new model();
        $this->productModel = new ProductRepository();
        $this->log = new Logger('goodsEdit');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/goodsEdit.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }

    //列表
    public function index($where)
    {
        $cron = $where;
        if (empty($cron['order'])) {
            // $cron['order'] = ['orderby' => 'id', 'orderdir' => 'desc'];
            $cron['order'] = ['orderby' => ['is_top' => 'asc', 'id' => 'desc']];
        }

        // $cron['where'] = $where;
        // var_dump($cron, 111111111);

        $data = $this->search($this->model, $cron, 1, 9000000);
        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => &$val) {
                $val['is_sort_edit'] = false;
            }
            $data['data'] = usfirstArr($data['data']);
        }
        return $data;
    }

    //添加
    public function add($data)
    {
        //必填 字段
        $mustField = [
            'name',
            'product_id',
            'main_pic'
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'name' => '商品名称不能为空',
            'product_id' => '产品不能为空',
            'main_pic' => '主图不能为空',
            'oblong_pic' => '长形图不能为空',
//            'detail_top_pic' => '详情头图不能为空',
        ];
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        $productData = $this->productModel->getOne(['id' => $insertData['product_id']]);
        if (empty($productData)) {
            if ($data->user->shop_id != $productData->shop_id) {
                return $this->returnMsg(2, '您无权添加该产品');
            }
            return $this->returnMsg(100, '未查询到产品');
        }
        $isTrue = $this->getOne(['name' => $insertData['name'], 'shop_id' => $data->user->shop_id]);
        if ($isTrue) {
            return $this->returnMsg(3, '该商品已添加');
        }
        if (isset($insertData['main_pic']) && strlen($insertData['main_pic']) > 1000) {
            $model = new UploadRepository();
            $resPic = $model->uploadBase64($data['main_pic']);
            if (empty($resPic)) {
                return [
                    'code' => 100,
                    'msg' => '上传失败',
                    'fileName' => ''
                ];
            }
            $insertData['main_pic'] = $resPic;
        }
        if (isset($insertData['oblong_pic']) && strlen($insertData['oblong_pic']) > 400) {
            $model = new UploadRepository();
            $resPic = $model->uploadBase64($data['oblong_pic']);
            if (empty($resPic)) {
                return [
                    'code' => 100,
                    'msg' => '上传长形图失败',
                    'fileName' => ''
                ];
            }
            $insertData['oblong_pic'] = $resPic;
        }
        if (isset($insertData['detail_top_pic']) && strlen($insertData['detail_top_pic']) > 400) {
            $model = new UploadRepository();
            $resPic = $model->uploadBase64($data['detail_top_pic']);
            if (empty($resPic)) {
                return [
                    'code' => 100,
                    'msg' => '上传详情头图失败',
                    'fileName' => ''
                ];
            }
            $insertData['detail_top_pic'] = $resPic;
        }
        if (!empty($insertData['goods_detail']) && strlen($insertData['goods_detail']) > 10000) {
            return $this->returnMsg(104, '上传数据太长,请检测上传的图片,请尽量使用上面图片上传按钮');
        }
        $insertData['product_name'] = $productData->name;
        $insertData['product_code'] = $productData->product_code;
        $insertData['product_type'] = $productData->product_type;
        // $operator = '移动';
        // if(!empty($productData->operator)){
        //   if($productData->operator == 1){
        //     $operator = '电信';
        //   }else if($productData->operator == 2){
        //     $operator = '联通';
        //   }else if($productData->operator == 3){
        //     $operator = '虚拟';
        //   }
        // }
        $insertData['product_operator'] = $productData->operator;
        $insertData['created_at'] = date('Y-m-d H:i:s');
        $insertData['created_by'] = $data->user->id;
        $insertData['created_by_name'] = $data->user->user_name;
        $insertData['shop_id'] = (!empty($data->user->shop_id) ? $data->user->shop_id : (!empty($data->user->id) ? $data->user->id : ''));


        $res = $this->model->insertGetId($insertData);
        // var_dump($res,555555555);
        // var_dump($data->user, 44444444444);
        // 商品创建 log
        $modelRemark = new GoodsRemarkRepository();
        $goodsInsertData = [
            'goods_id' => $res,
            'remark' => $data->user->user_name . '创建商品<br/>',
            'shop_id' => $data->user->shop_id
        ];
        $modelRemark->add($goodsInsertData);
        if ($res) {
            return $this->returnMsg(200, '添加成功');
        }
        return $this->returnMsg(1, '添加失败');
    }

    //删除
    public function del($where)
    {
        $flag = true;
        $msg = '未知错误';
        $code = 1;
        if (empty($where)) {
            $flag = false;
            $msg = '删除条件不能为空';
            $code = 2;
        }
        if ($flag) {
            $res = $this->model->where($where)->get();
            if (!$res) {
                $flag = false;
                $msg = '未查询到数据';
                $code = 3;
            }
        }
        if ($flag) {
            $del = $this->model->where($where)->delete();
            if ($del) {
                $msg = '删除成功';
                $code = 200;
            }
        }
        return $this->returnMsg($code, $msg);
    }

    //修改
    public function edit($where, $data, $isMust = false)
    {
        // $params = $data ->all();
        $params = $data;
        if (method_exists($data, 'all')) {
            $params = $data->all();
        }
        $this->log->info('商品修改查询条件:' . json_encode($where) . '修改参数:' . json_encode($params));
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        //过滤字段
        //过滤字段
        $optionalFields = $this->model->getTableField();
        $field = $this->getRealData($data, [], $optionalFields, []);
        // if (!empty($field['main_pic']) && is_string($field['main_pic']) && file_exists('.' . $field['main_pic'])) {
        //   unset($field['main_pic']);
        // }
        if (!empty($field['main_pic']) && strlen($field['main_pic']) > 1000) {
            $model = new UploadRepository();
            $resPic = $model->uploadBase64($data['main_pic']);
            // var_dump($resPic);
            if (empty($resPic)) {
                return [
                    'code' => 100,
                    'msg' => '上传失败',
                    'fileName' => ''
                ];
            }
            $field['main_pic'] = $resPic;
        }
        if (!empty($field['oblong_pic']) && strlen($field['oblong_pic']) > 400) {
            $model = new UploadRepository();
            $resPic = $model->uploadBase64($data['oblong_pic']);
            // var_dump($resPic);
            if (empty($resPic)) {
                return [
                    'code' => 100,
                    'msg' => '长形图上传失败',
                    'fileName' => ''
                ];
            }
            $field['oblong_pic'] = $resPic;
        }
        if (!empty($field['detail_top_pic']) && strlen($field['detail_top_pic']) > 400) {
            $model = new UploadRepository();
            $resPic = $model->uploadBase64($data['detail_top_pic']);
            // var_dump($resPic);
            if (empty($resPic)) {
                return [
                    'code' => 100,
                    'msg' => '详情头图上传失败',
                    'fileName' => ''
                ];
            }
            $field['detail_top_pic'] = $resPic;
        }
        if (!empty($field['goods_detail']) && strlen($field['goods_detail']) > 10000) {
            return $this->returnMsg(104, '上传数据太长,请检测上传的图片,请尽量使用上面图片上传按钮');
        }
        if (empty($field['main_pic'])) {
            unset($field['main_pic']);
        }
        if (!empty($field['product_id'])) {
            $productData = $this->productModel->getOne(['id' => $field['product_id']]);
            if (empty($productData)) {
                if ($data->user->shop_id != $productData->shop_id) {
                    return $this->returnMsg(2, '您无权添加该产品');
                }
                return $this->returnMsg(100, '未查询到产品');
            }
            $field['product_name'] = $productData->name;
            $field['product_code'] = $productData->product_code;
            $field['product_type'] = $productData->product_type;
            // $operator = '移动';
            // if(!empty($productData->operator)){
            //   if($productData->operator == 1){
            //     $operator = '电信';
            //   }else if($productData->operator == 2){
            //     $operator = '联通';
            //   }else if($productData->operator == 3){
            //     $operator = '虚拟';
            //   }
            // }
            $field['product_operator'] = $productData->operator;
        }
        //查询是否存在
        $isTrue = $this->model->where($where)->first();
        if (!$isTrue) {
            return $this->returnMsg(3, '未查询到商品');
        }
        // 当上架的时候 判断
        if (isset($field['status']) && $field['status'] == '0' && !empty($isTrue->sup_goods_id)) {
            // 当代理上新套餐时  判断上游是否上架
            $whereIsOk = [
                'id' => $isTrue->sup_goods_id
            ];
            $isTrueOk = $this->model->where($whereIsOk)->first();
            if ($isTrueOk->status != 0) {
                return $this->returnMsg(102, '该产品供应商已下架');
            }
        }
        $remark = '';
        foreach ($field as $key => $v) {
            // 用户信息 + 商品信息 + 产品信息
            if ($key == 'status' || $key == 'goods_code' || $key == 'product_code' || $key == 'product_id' || $key == 'goods_price' || $key == 'is_app_all' || $key == 'is_app') {
                if ($isTrue->$key != $v) {
                    $isedit = true;
                    if ($key == 'status') {
                        if ($v == 0) {
                            $remark .= $data->user->user_name . '将状态修改成上架';
                        } else {
                            $remark .= $data->user->user_name . '将状态修改成下架';
                        }
                    } else if ($key == 'goods_code') {
                        $remark .= $data->user->user_name . '将商品编码' . $isTrue->$key . '修改为' . $v;
                    } else if ($key == 'product_code') {
                        $remark .= $data->user->user_name . '将产品编码' . $isTrue->$key . '修改为' . $v;
                    } elseif ($key == 'goods_price') {
                        $remark .= $data->user->user_name . '将价格' . $isTrue->$key . '修改为' . $v;
                    } elseif ($key == 'is_app') {
                        $str = '下架';
                        if ($v == 0) {
                            $str = '上架';
                        } else {
                            $str = '下架';
                        }
                        $remark .= $data->user->user_name . '将小风车' . $isTrue->$key . '修改为' . $str;
                    } elseif ($key == 'is_app_all') {
                        $str = '下架';
                        if ($v == 0) {
                            $str = '上架';
                        } else {
                            $str = '下架';
                        }
                        $remark .= $data->user->user_name . '将小程序' . $isTrue->$key . '修改为' . $str;
                    }
                }
            }
        }
        if (empty($field['sort'])) {
            $field['sort'] = 0;
        }
        // 先修改本地的
        // 存入日志
        $modelRemark = new GoodsRemarkRepository();
        //先查询是否存在
        $res = $this->model->where($where)->update($field);
        $this->log->info('商品修改查询条件:' . json_encode($where) . '修改参数:' . json_encode($params) . '返回结果:' . $res);
        // 跟随主账号一同上下架  上架是0  下架是1
        if (isset($field['status']) || !empty($data['is_sync'])) {
            $shop_str = $isTrue->id;
            // 出现两种情况
            if (!empty($isTrue->goods_str)) {
                $shop_str = $isTrue->goods_str . '.' . $isTrue->id;
            }
            if (empty($isTrue->goods_str)) {
                $shop_str = '0.' . $shop_str;
            }
            if (!empty($shop_str)) {
                $where = [];
                $where[] = [
                    'goods_str', 'like', $shop_str . '.%'
                ];
                // var_dump($where);
                // 将代理的商品下架

                $fenxiaoGoods = $this->model->where($where)->get();
                if (($fenxiaoGoods)) {
                    foreach ($fenxiaoGoods as $key => $v) {
                        if ($v->id == $isTrue->id) {
                            continue;
                        }

                        if (!empty($data['is_sync'])) {
                            $remark .= '并且下面所有的分销商商品强制更新';
                        } else {
                            $remark .= '并且下面所有的分销商商品修改了';
                        }
                        $goodsInsertData = [
                            'goods_id' => $v->id,
                            'remark' => '供应商商品修改了<br/>'
                        ];
                        $whereInsertData = [
                            'goods_id' => $v->id
                        ];
                        $modelRemark->edit($whereInsertData, $goodsInsertData);
                    }
                }
                $this->model->where($where)->update($field);
            }
        }

        $goodsInsertData = [
            'goods_id' => $isTrue->id,
            'remark' => $remark,
            'shop_id' => $isTrue->shop_id
        ];
        $whereInsertData = [
            'goods_id' => $isTrue->id
        ];
        // var_dump($goodsInsertData, 11111111111);
        $modelRemark->edit($whereInsertData, $goodsInsertData);
        //先查询是否存在
        // $res = $this->model->where($where)->update($field);
        if ($isMust && $res) {
            return $this->returnMsg(200, '修改成功');
        }
        if (!$isMust) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(3, '请重新修改');
    }

    //列表查询
    public function lists($where = [], $page = 1, $limit = 10)
    {
        $res = $this->search($this->model, $where, $page, $limit);

        return $res;
    }

    public function getOne($where, $field = ['*'])
    {
        return $this->model->where($where)->select($field)->first();
    }

    //分销商获取供应商的商品信息
    public function addSuppilerGoods($data)
    {
        if (empty($data['goods_id'])) {
            return $this->returnMsg(1, '未查询到商品');
        }
        $where = [
            'id' => $data['goods_id'],
        ];
        $godsData = $this->getOne($where, ['name', 'goods_code', 'product_code', 'product_name', 'product_id', 'goods_point', 'settle_require', 'main_pic', 'goods_detail', 'goods_remark', 'remark', 'shop_str', 'shop_id', 'goods_str', 'down_str', 'shop_name_str', 'shop_id_str', 'sup_goods_name', 'sup_goods_id', 'sup_goods_id_str', 'sup_shop_id', 'sup_shop_name', 'shop_id', 'monthly', 'flow', 'voice', 'goods_price', 'sort', 'tishi', 'is_trun', 'is_top', 'is_select_number', 'is_app_all', 'aperator']);
        if (empty($godsData)) {
            return $this->returnMsg(2, '未查询到商品');
        }
        $goodsData = json_decode(json_encode($godsData), true);

        $goodsData['goods_str'] = trim($goodsData['goods_str'], '.') . '.' . $data['goods_id'] . '.';
        // var_dump($goodsData, 111111111);
        // var_dump($goodsData['goods_str'], 22222222222);
        //判断他是否存在
        $isTrue = $this->getOne(['shop_id' => $data['shop_id'], 'goods_str' => $goodsData['goods_str']]);
        if ($isTrue) {
            return $this->returnMsg(3, '您已将这个产品添加到该产品中');
        }
        // 修改上游的str
        $update = [];
        $update = ['down_str' => trim($godsData['down_str'], '.') . '.' . $data['user']['shop_id'] . '.'];
        $this->edit(['id' => $data['goods_id']], $update);
        $goodsData['down_str'] = 0;
        $goodsData['shop_str'] = trim($goodsData['shop_str'], '.') . '.' . $data['shopId'] . '.';
        $goodsData['shop_name'] = $data['shop_name'];
        $goodsData['created_by'] = $data['user']['id'];
        $goodsData['created_by_name'] = $data['user']['name'];
        $goodsData['created_at'] = date('Y-m-d H:i:s');
        $goodsData['product_code'] = ''; // 产品信息全部清空
        $goodsData['product_name'] = ''; // 产品信息 全部清空
        $goodsData['product_id'] = 0; // 产品信息全部清空
        $goodsData['is_app'] = 1;
        // 需要查询到shop_name
        if (empty($goodsData['shop_id_str'])) {
            $isshopId = true;
        }
        $goodsData['shop_name_str'] = $goodsData['shop_name_str']; // 店铺名称字符串
        $goodsData['shop_id_str'] = $goodsData['shop_id_str']; // 店铺id 字符串
        if (!empty($isshopId)) {
            $goodsData['shop_name_str'] .= '.' . $data['supplier_name'] . '.'; // 店铺名称字符串
            $goodsData['shop_id_str'] .= '.' . $goodsData['shop_id'] . '.'; // 店铺id 字符串
        }
        $goodsData['shop_name_str'] .= $data['shop_name'] . '.'; // 店铺名称字符串
        $goodsData['shop_id_str'] .= $data['user']['shop_id'] . '.'; // 店铺id 字符串


        $goodsData['sup_goods_name'] = $goodsData['name']; // 供应商商品名称
        $goodsData['sup_goods_id'] = $data['goods_id']; // 供应商商品名称
        $isGoodsStr = $goodsData['sup_goods_id_str'];
        if (empty($goodsData['sup_goods_id_str'])) {
            $isGoodsStr .= '.' . $data['goods_id'] . '.'; // 供应商商品字符串
        }

        $goodsData['sup_shop_id'] = $goodsData['shop_id']; // 供应商店铺id
        $goodsData['sup_shop_name'] = $data['supplier_name']; // 供应商店铺名称
        $goodsData['shop_id'] = $data['user']['shop_id'];
        $res = $this->model->insertGetId($goodsData);
        // var_dump($data, 77777777777);
        $modelRemark = new GoodsRemarkRepository();
        $goodsInsertData = [
            'goods_id' => $res,
            'remark' => $data['supplier_name'] . '创建供应商商品<br/>',
            'shop_id' => $data['shop_id']
        ];
        $modelRemark->add($goodsInsertData);
        if ($res) {
            $update = [
                'sup_goods_id_str' => $isGoodsStr . $res . '.',
            ];
            $isTrues = $this->model->where(['id' => $res])->update($update);
            return $this->returnMsg(200, '添加成功');
        }
        return $this->returnMsg(1, '添加失败');
    }
}
